package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.Student;
import com.scuec.trainingmanagementsys.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
@CrossOrigin
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 整表查询
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllStudents() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Student> students = studentService.getAllStudents();
            result.put("message", "整表学生信息查询成功");
            result.put("data", students);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "整表学生信息查询失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据学号查询
    @GetMapping("find/{studentNumber}")
    public ResponseEntity<Map<String, Object>> getStudentByNumber(@PathVariable String studentNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            Student student = studentService.getStudentByNumber(studentNumber);
            if (student != null) {
                result.put("message", "根据学号查询学生信息成功");
                result.put("data", student);
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "根据学号查询学生信息失败，未找到对应学号的学生");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "根据学号查询学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据姓名模糊查询
    @GetMapping("findByName/{studentName}")
    public ResponseEntity<Map<String, Object>> getStudentsByName(@PathVariable String studentName) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Student> students = studentService.getStudentsByName(studentName);
            result.put("message", "根据姓名模糊查询学生信息成功");
            result.put("data", students);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "根据姓名模糊查询学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据性别查询
    @GetMapping("findByGender/{gender}")
    public ResponseEntity<Map<String, Object>> getStudentsByGender(@PathVariable String gender) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Student> students = studentService.getStudentsByGender(gender);
            result.put("message", "根据性别查询学生信息成功");
            result.put("data", students);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "根据性别查询学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据学院查询
    @GetMapping("findByCollege/{college}")
    public ResponseEntity<Map<String, Object>> getStudentsByCollege(@PathVariable String college) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Student> students = studentService.getStudentsByCollege(college);
            result.put("message", "根据学院查询学生信息成功");
            result.put("data", students);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "根据学院查询学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 多条件查询
    @GetMapping("/conditions")
    public ResponseEntity<Map<String, Object>> getStudentsByConditions(@RequestParam(required = false) String studentNumber,
                                                                       @RequestParam(required = false) String studentName,
                                                                       @RequestParam(required = false) String gender,
                                                                       @RequestParam(required = false) String college) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Student> students = studentService.getStudentsByConditions(studentNumber, studentName, gender, college);
            result.put("message", "多条件查询学生信息成功");
            result.put("data", students);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "多条件查询学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 删除功能
    @DeleteMapping("delete/{studentNumber}")
    public ResponseEntity<Map<String, Object>> deleteStudentByNumber(@PathVariable String studentNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rowsAffected = studentService.deleteStudentByNumber(studentNumber);
            if (rowsAffected > 0) {
                result.put("message", "删除指定学号的学生信息成功");
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "删除指定学号的学生信息失败，未找到对应学号的学生");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "删除指定学号的学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 修改信息功能
    @PutMapping("/update/{studentNumber}")
    public ResponseEntity<Map<String, Object>> updateStudent(@RequestBody Map<String, Object> studentData) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求数据中获取学生学号
            String studentNumber = (String) studentData.get("studentNumber");
            if (studentNumber == null) {
                result.put("message", "学号不能为空");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 创建Student对象并设置非密码字段
            Student student = new Student();
            student.setStudentNumber(studentNumber);
            student.setStudentName((String) studentData.get("studentName"));
            student.setGender((String) studentData.get("gender"));
            student.setCollege((String) studentData.get("college"));
            student.setMajor((String) studentData.get("major"));
            student.setClassInfo((String) studentData.get("classInfo"));
            student.setEmail((String) studentData.get("email"));
            student.setPhone((String) studentData.get("phone"));

            // 检查是否需要更新密码
            if (studentData.containsKey("studentPassword") &&
                    studentData.get("studentPassword") != null) {
                student.setStudentPassword((String) studentData.get("studentPassword"));
            }

            int rowsAffected = studentService.updateStudent(student);
            if (rowsAffected > 0) {
                result.put("message", "修改学生信息成功");
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "修改学生信息失败，未找到对应学号的学生");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "修改学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    // 插入信息功能
    @PostMapping("/insert")
    public ResponseEntity<Map<String, Object>> insertStudent(@RequestBody Student student) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rowsAffected = studentService.insertStudent(student);
            if (rowsAffected > 0) {
                result.put("message", "插入学生信息成功");
                return new ResponseEntity<>(result, HttpStatus.CREATED);
            } else {
                result.put("message", "插入学生信息失败，可能是数据格式或约束问题");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            result.put("message", "插入学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 多选删除功能
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteStudentsByNumbers(@RequestBody List<String> studentNumbers) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rowsAffected = studentService.deleteStudentsByNumbers(studentNumbers);
            if (rowsAffected > 0) {
                result.put("message", "批量删除学生信息成功");
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "批量删除学生信息失败，未找到任何对应学号的学生");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "批量删除学生信息失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 学生登录接口
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> studentLogin(@RequestBody Map<String, String> loginInfo) {
        Map<String, Object> result = new HashMap<>();
        try {
            String studentNumber = loginInfo.get("studentNumber");
            String studentPassword = loginInfo.get("studentPassword");
            Student student = studentService.getStudentByNumberAndPassword(studentNumber, studentPassword);
            if (student != null) {
                result.put("message", "学生登录成功");
                result.put("data", student);
                result.put("success", true);
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "学生登录失败，学号或密码错误");
                result.put("success", false);
                return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
            }
        } catch (Exception e) {
            result.put("message", "学生登录失败: " + e.getMessage());
            result.put("success", false);
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 新增：学生注册接口
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerStudent(@RequestBody Map<String, String> regInfo) {
        Map<String, Object> result = new HashMap<>();
        try {
            String studentNumber = regInfo.get("studentNumber");
            String studentName = regInfo.get("studentName");
            String password = regInfo.get("password");
            String gender = regInfo.get("gender");
            String college = regInfo.get("college");
            String major = regInfo.get("major");
            String classInfo = regInfo.get("classInfo");
            String email = regInfo.get("email");
            String phone = regInfo.get("phone");

            // 基础校验
            if (studentNumber == null || studentNumber.isEmpty()) {
                result.put("message", "学号不能为空");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }
            if (studentName == null || studentName.isEmpty()) {
                result.put("message", "姓名不能为空");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }
            if (password == null || password.isEmpty()) {
                result.put("message", "密码不能为空");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 检查学号是否已存在
            Student existing = studentService.getStudentByNumber(studentNumber);
            if (existing != null) {
                result.put("message", "学号已存在");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 创建学生对象
            Student student = new Student();
            student.setStudentNumber(studentNumber);
            student.setStudentName(studentName);
            student.setStudentPassword(password);
            student.setGender(gender != null ? gender : "");
            student.setCollege(college != null ? college : "");
            student.setMajor(major != null ? major : "");
            student.setClassInfo(classInfo != null ? classInfo : "");
            student.setEmail(email != null ? email : "");
            student.setPhone(phone != null ? phone : "");

            // 插入数据库
            int rows = studentService.insertStudent(student);
            if (rows > 0) {
                result.put("message", "学生注册成功");
                result.put("success", true);
                return new ResponseEntity<>(result, HttpStatus.CREATED);
            } else {
                result.put("message", "学生注册失败");
                return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            result.put("message", "学生注册失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取学生个人资料
    @GetMapping("/profile/{studentNumber}")
    public ResponseEntity<Map<String, Object>> getStudentProfile(@PathVariable String studentNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            Student student = studentService.getStudentProfile(studentNumber);
            if (student != null) {
                result.put("message", "获取学生个人资料成功");
                result.put("data", student);
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "未找到该学生资料");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "获取学生个人资料失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取学生总数
    @GetMapping("/count")
    public ResponseEntity<Map<String, Object>> getStudentCount() {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = studentService.getStudentCount();
            result.put("message", "获取学生总数成功");
            result.put("data", count);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "获取学生总数失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
